<template>
  <el-dialog
    v-el-drag-dialog
    width="800px"
    :visible="showDialog"
    title="添加成员"
    custom-class="modal-form"
    :show-close="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="onFormClosed"
  >
    <el-form
      ref="formUserReference"
      :model="dataFilter"
      style="height: 500px;"
    >
      <el-form-item
        prop="filter"
        label="搜索"
        label-width="70%"
      >
        <el-input
          v-model="dataFilter.filter"
          @input="refreshPagedData"
        />
      </el-form-item>
      <el-table
        ref="userTable"
        v-loading="dataLoading"
        row-key="id"
        :data="dataList"
        border
        fit
        highlight-current-row
        height="330px"
        style="width: 100%;"
        @sort-change="handleSortChange"
        @selection-change="onSelectionChanged"
      >
        <el-table-column
          type="selection"
          width="50"
          align="center"
          reserve-selection
        />
        <el-table-column
          label="用户名称"
          prop="userName"
          sortable
          width="110px"
          align="center"
        >
          <template slot-scope="{row}">
            <span>{{ row.userName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="真实名称"
          prop="surname"
          width="110px"
          align="center"
        >
          <template slot-scope="{row}">
            <span>{{ row.surname }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="显示名称"
          prop="name"
          width="110px"
          align="center"
        >
          <template slot-scope="{row}">
            <span>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="邮箱"
          prop="email"
          sortable
          min-width="180"
          align="center"
        >
          <template slot-scope="{row}">
            <span>{{ row.email }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="手机"
          prop="phoneNumber"
          width="140px"
          align="center"
        >
          <template slot-scope="{row}">
            <span>{{ row.phoneNumber }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="锁定时间"
          prop="lockoutEnd"
          sortable
          width="140px"
          align="center"
        >
          <template slot-scope="{row}">
            <span>{{ row.lockoutEnd | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          prop="creationTime"
          sortable
          width="140px"
          align="center"
        >
          <template slot-scope="{row}">
            <span>{{ row.creationTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        :total="dataTotal"
        :page.sync="currentPage"
        :limit.sync="pageSize"
        @pagination="refreshPagedData"
      />

      <el-form-item>
        <el-button
          class="cancel"
          type="info"
          @click="onFormClosed"
        >
          取消
        </el-button>
        <el-button
          class="confirm"
          type="primary"
          icon="el-icon-check"
          @click="onSave"
        >
          确定
        </el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { getUnaddedUsers, addUsers } from '@/api/organizationunit'
import { abpPagerFormat } from '@/utils'
import EventBusMiXin from '@/mixins/EventBusMiXin'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'UserReference',
  components: {
    Pagination
  },
  directives: { elDragDialog },
  mixins: [EventBusMiXin],
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    organizationUnitId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      organizationUnit: { },
      dialogFormVisible: false,
      dialogStatus: '',
      ouAddRole: {},
      dataFilter: {},
      ouAddUser: {
        userIds: []
      },
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined,
        sorting: 'ExecutionTime'
      },
      dataTotal: 0,
      pageSize: 10,
      currentPage: 0,
      dataLoading: false,
      dataList: [],
      textMap: {
        update: '编辑',
        create: '添加',
        preview: '查看'
      },
      rules: {
        executionTime: [{ required: true, message: '必须填写', trigger: 'blur' }],
        executionDuration: [{ required: true, message: '必须填写', trigger: 'blur' }]
      },
      downloadLoading: false,
      loading: false,
      tempRoute: {},
      activeNames: ['1']
    }
  },
  watch: {
    showDialog() {
      if (this.showDialog) {
        this.refreshPagedData()
      }
    }
  },
  destroyed() {
    this.unSubscribe('onUserOrganizationUintChanged')
  },
  created() {
    this.subscribe('onUserOrganizationUintChanged', this.refreshPagedData)
  },
  methods: {
    refreshPagedData() {
      this.getPagedList({})
    },
    processDataFilter() {
      this.dataFilter.skipCount = abpPagerFormat(this.currentPage, this.pageSize)
    },
    getPagedList(dataFilter) {
      getUnaddedUsers(this.organizationUnitId, dataFilter).then(res => {
        this.dataList = res.data.items
      })
    },
    onSelectionChanged(selection) {
      this.ouAddUser.userIds.length = 0
      selection.forEach(row => {
        if (!this.isInOrganizationUnit(row.id)) {
          this.addUser(row.id)
        }
      })
    },
    onSave() {
      if (this.ouAddUser.userIds.length > 0) {
        addUsers(this.organizationUnitId, this.ouAddUser).then(() => {
          this.ouAddUser.userIds.length = 0
          this.refreshPagedData()
          // 层次太深了,通过事件的方式来刷新列表
          this.trigger('onUserOrganizationUintChanged')
        })
      }
    },
    onFormClosed() {
      if (this.ouAddUser.userIds.length > 0) {
        this.$confirm('是否取消组织机构成员编辑',
          '提示', {
            callback: (action) => {
              if (action === 'confirm') {
                this.resetFields()
                this.$emit('closed')
              }
            }
          })
      } else {
        this.resetFields()
        this.$emit('closed')
      }
    },
    resetFields() {
      const formUserReference = this.$refs.formUserReference
      formUserReference.resetFields()
      const userTable = this.$refs.userTable
      userTable.clearSelection()
      this.ouAddUser.userIds.length = 0
    },
    handleSortChange: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}`
        ? 'ascending'
        : sort === `-${key}`
          ? 'descending'
          : ''
    },
    isInOrganizationUnit(userId) {
      return this.ouAddUser.userIds.some(id => id === userId)
    },
    addUser(userId) {
      this.ouAddUser.userIds.push(userId)
    },
    removeUser(userId) {
      const index = this.ouAddUser.userIds.findIndex(id => id === userId)
      this.ouAddUser.userIds.splice(index, 1)
    }
  }
}
</script>

<style scoped>
.confirm {
  position: absolute;
  right: 10px;
  width:100px;
}
.cancel {
  position: absolute;
  right: 120px;
  width:100px;
}
</style>
